from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.db.models.signals import pre_save
from django.dispatch import receiver
import re

# 用户角色常量
ROLE_SUPER_ADMIN = 'super_admin'
ROLE_ADMIN = 'admin'
ROLE_USER = 'user'

ROLE_CHOICES = (
    (ROLE_SUPER_ADMIN, '超级管理员'),
    (ROLE_ADMIN, '管理员'),
    (ROLE_USER, '普通用户'),
)

# 新增性别常量与选项
GENDER_MALE = 'male'
GENDER_FEMALE = 'female'
GENDER_CHOICES = (
    (GENDER_MALE, '男'),
    (GENDER_FEMALE, '女'),
)

class CustomUserManager(BaseUserManager):
    def create_user(self, username, email=None, password=None, **extra_fields):
        if not username:
            raise ValueError('用户名必须设置')
        email = self.normalize_email(email)
        user = self.model(username=username, email=email, **extra_fields)
        user.set_password(password)  # 自动加密密码
        user.save(using=self._db)
        return user
    
    def create_superuser(self, username, email=None, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        extra_fields.setdefault('role', ROLE_SUPER_ADMIN)
        
        if extra_fields.get('is_staff') is not True:
            raise ValueError('超级用户必须设置is_staff=True')
        if extra_fields.get('is_superuser') is not True:
            raise ValueError('超级用户必须设置is_superuser=True')
        
        return self.create_user(username, email, password, **extra_fields)

class User(AbstractUser):
    role = models.CharField(max_length=20, choices=ROLE_CHOICES, default=ROLE_USER, verbose_name='角色')
    phone = models.CharField(max_length=20, blank=True, null=True, verbose_name='手机号')
    # 新增性别字段
    gender = models.CharField(max_length=10, choices=GENDER_CHOICES, blank=True, null=True, verbose_name='性别')
    avatar = models.ImageField(upload_to='avatars/', blank=True, null=True, verbose_name='头像')

    def __str__(self):
        return self.username
    
    def is_super_admin(self):
        return self.role == ROLE_SUPER_ADMIN
    
    def is_admin(self):
        return self.role == ROLE_ADMIN
    
    def is_normal_user(self):
        return self.role == ROLE_USER

# 自定义ID分配规则的信号处理
@receiver(pre_save, sender=User)
def allocate_user_id(sender, instance, **kwargs):
    # 如果是新用户（没有ID）
    if not instance.pk:
        # 根据角色分配ID
        if instance.role == ROLE_SUPER_ADMIN:
            # 超级管理员ID固定为1
            instance.pk = 1
        elif instance.role == ROLE_ADMIN:
            # 管理员ID范围10-100（包含10和100）
            last_admin = User.objects.filter(role=ROLE_ADMIN).order_by('-id').first()
            if last_admin and 10 <= last_admin.id < 100:
                instance.pk = last_admin.id + 1
                if instance.pk > 100:  # 确保不超过100
                    instance.pk = 100
            else:
                # 从10开始找第一个可用的ID
                for i in range(10, 101):
                    if not User.objects.filter(id=i).exists():
                        instance.pk = i
                        break
        else:  # 普通用户
            # 普通用户ID从1000开始（包含1000）
            last_user = User.objects.filter(role=ROLE_USER).order_by('-id').first()
            if last_user and last_user.id >= 1000:
                instance.pk = last_user.id + 1
            else:
                instance.pk = 1000
